#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import sys,signal
import os, time

from openchord import ID
from openchord import URL, Chord, Node
from openchord.help import logging

logger = logging.getLogger('OpenChord')
logger.setLevel(logging.LEVEL_DEBUG)

root_url_str = 'octcp://127.0.0.1:43000/test'

chord = Chord()

chord.join(None, root_url_str, 0)
print chord.toPrettyString()

ports = ((43010,1), )

def run_chord(port, id) :
    url_str = 'octcp://127.0.0.1:%d/test' % port
    chord = Chord()
    chord.join(root_url_str, url_str, id)
    print chord.toPrettyString()

    chord.leave()
    chord = None
    ## run_chord()

children = []

for port,id in ports :
    pid = os.fork()
    if pid == 0 :
        ## child
        run_chord(port, id)
        time.sleep(1)
        sys.exit(0)
    else :
        ## parent
        children.append( pid )


try :
    os.wait()
except KeyboardInterrupt :
    print 'Keyboard Interrupt. ending ...'
    for pid in children :
        try :
            os.kill(pid, signal.SIGTERM)
        except :
            pass
except :
    for pid in children :
        try :
            os.kill(pid, signal.SIGTERM)
        except :
            pass

logger.info('chord is leaving ...')
if chord :
    chord.leave()
    chord = None

logger.info('done.')
sys.exit(0)
    

